import { resolve } from 'core-js/fn/promise';
import { replace } from 'lodash';
import { Route as config } from 'public/config/base.config'; 
import store from '@/assets/js/store/store.js';
class RouterInit {
    constructor(props){
        this.$router = props.options || {};
        this.$config = config;
        this.$open = !!config.open ? (() => { 
            if(Array.isArray(config.open)) return config.open
            else return config.open.split(",");
        })() : [];
        this.$options = !!config.options ? (() => {
            if(Array.isArray(config.options))    return config.options;
            else throw new Error("===> base.config.js  Route.options Typeof Array ?");
        })() : [];
    }
    // 判断参数是否已经挂载完成
    hasRouters (router){
        let routes = router.options.routes;
        let openRoutes = [], flg = true;
        // 找出必须存在子路由的配置数据
        routes.forEach(element => {
            let _key = element.path.split("/")[1];
            if(this.$open.indexOf(_key) != -1) openRoutes.push(element);
        });
        if(openRoutes.length > 0){
            // 若需配置路由需要存在参数
            openRoutes.forEach(_ => {
                if(flg) flg = _.hasOwnProperty("children") && _.children.length > 0;
            })
        }
        return flg;
    }
    // 对router 数据进行挂载
    initRoutes ( router, to, next ){
        const routes = this.$router.routes;
        if(!!this.$config.dataType)  throw new Error("Custome Config Error：public/config/base.config.js Route properties dataType is null!");
        if(typeof this.$config.dataType === 1) this.setHttpRouteData( to, from);
        else {
            router.addRoutes(this.setLocalRouteData( routes));
        }
        store.commit("setGlobalRoute", routes);
        next({path: to.path, replace: true});
        store.commit("setGlobalCurrentRoute", to);
    }
    // 本地数据封装
    setLocalRouteData ( routes){
        let resultRoutes = Object.assign([], routes);
        resultRoutes.forEach(_ => {
            let key = _.path.substring( 1, _.path.length);
            if(this.$open.indexOf(key) != -1){
                this.$options.forEach(k => {
                    if(key === k.path.substring( 1, k.path.length)){
                        _["children"] = this.setRouteData(k.data || []);
                    }
                });
            }
        });
        resultRoutes.push({ path: '*', component: () => import('@/compoments/api/404') });
        return resultRoutes;
    }

    // 服务器数据的获取
    setHttpRouteData ( to, from){

    }

    // 设置数据
    setRouteData (data){
        let children = [];
        data.forEach(_ => {
            if(!!_.src){ //@/page
                children.push({
                    path: _.path,
                    meta: {title: _.title || "",icon: _.icon || null},
                    component: () => Promise.resolve(require(`page/${_.src}.vue`))
                });
            }
        });
        return children;
    }
}
export default RouterInit;